package org.megha.blog.example.threads;

/**
 * Increments the given counters a given number of times.
 *
 * @author megha
 */
public class CounterIncrementor implements Runnable {

	private final int times;
	private final ThreadSafeCounter safeCounter;
	private final ThreadUnsafeCounter unsafeCounter;

	public CounterIncrementor(ThreadUnsafeCounter unsafeCounter,
			ThreadSafeCounter safeCounter, int times) {
		this.unsafeCounter = unsafeCounter;
		this.safeCounter = safeCounter;
		this.times = times;
	}

	@Override
	public void run() {
		for(int i = 0; i < times; i++) {
			safeCounter.increment();
			// need to run in a synchronized block to ensure that two
			// parallel calls to increment are never made
			synchronized (unsafeCounter) {
				unsafeCounter.increment();
			}
		}
	}
}
